use crate::{
    mesh::{MeshData, TexVertex},
    texture::ImageData
};

pub fn load_model(path: &str) -> anyhow::Result<MeshData<TexVertex>> {
    eprintln!("load_model: begin");

    let (meshes, _) = tobj::load_obj(path, &tobj::LoadOptions {
        triangulate: true,
        single_index: true,
        ..Default::default()
    })?;

    eprintln!("load_model: meshes:");

    for mesh in &meshes {
        eprintln!("  {}", mesh.name);
    }

    let mesh = meshes
        .into_iter()
        .next()
        .ok_or(anyhow::Error::msg("No meshes found in model"))?
        .mesh;

    let vertices = (0..mesh.positions.len() / 3).map(|i| TexVertex {
        position: [
            mesh.positions[i * 3],
            mesh.positions[i * 3 + 1],
            mesh.positions[i * 3 + 2]
        ],
        tex_coords: [
            mesh.texcoords[i * 2],
            1.0 - mesh.texcoords[i * 2 + 1]
        ]
    }).collect::<Vec<_>>();

    let indices = mesh.indices;

    eprintln!("load_model: end");

    Ok(MeshData { vertices, indices })
}

pub fn load_image(path: &str) -> anyhow::Result<ImageData> {
    use image::GenericImageView;

    eprintln!("load_image: begin");

    let img = image::open(path)?;
    let rgba = img.to_rgba8();
    let dimensions = img.dimensions();

    eprintln!("load_image: end");

    Ok(ImageData {
        width: dimensions.0,
        height: dimensions.1,
        data: rgba.into_vec()
    })
}
